import { JSEncrypt } from 'jsencrypt'
import { RSAKey } from 'jsencrypt/lib/lib/jsbn/rsa'
import { parseBigInt } from 'jsencrypt/lib/lib/jsbn/jsbn'

RSAKey.prototype.decrypt = function (ctext) {
  let c = parseBigInt(ctext, 16)
  let m = this.doPublic(c)
  //let m = this.doPrivate(c);
  if (m == null) {
    return null
  }

  return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3)
}

function pkcs1unpad2(d, n) {
  let b = d.toByteArray()
  let i = 0
  while (i < b.length && b[i] == 0) {
    ++i
  }
  //注释即可
  // if (b.length - i != n - 1 || b[i] != 2) {
  //     return null;
  // }
  ++i
  while (b[i] != 0) {
    if (++i >= b.length) {
      return null
    }
  }
  let ret = ''
  while (++i < b.length) {
    let c = b[i] & 255
    if (c < 128) { // utf-8 decode
      ret += String.fromCharCode(c)
    } else if ((c > 191) && (c < 224)) {
      ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63))
      ++i
    } else {
      ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63))
      i += 2
    }
  }
  return ret
}

const privateKey = ``

const pubKey = `-----BEGIN PUBLIC KEY-----MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvqKWWinXnoZJtmCinesPzRD1RnSgpshZ/JpWEAWDD3dSNsYuMLyp5GWASPynLyvDcnpn+WFb+A2q/G9OshgTZKdJd/y1k92MQtfswBItRRVrg1wwk+wnzarxpvZ+rDgujoK1LhaOWDj+VahFejArLLEpmQ/4gBTbfHYDFsdtNcCZtTaRc+fLK2DMxMdnUqWn4ObIQrpWI9BQNvjisYqTQ1v0moYAE1+FafwkUzbXjfMnHZBUjSDu/UbjTS82mbc1cHLV9+fIcbJg7KwpwFzkGeK51qlUsLFaBMQjsNRVKC+qIY7yJf9pMyBHMftmCrTcEnmKmVeEwYLemhU0gYRyczH/nHYHNGscErZWHnn2DPsBd4Xvb4rcW81MrG0ul6Zl5dW3myln+ANQN/QDc4LsV/09/kyJfs4z3D/nisLsLAwN6u5lcMGEQCHXHPIPpkagKVTR5FqQ3PeNK1LavXWkpQ2kXO7CKLsfzWMyb+ZkAuKSDCTNJSAhlsoSqtaFr/sVloIktoF5AsIfJpzfrRjnCEsKSD3FYu58a9z1ipKBJmOSjBQ2CRJZx4h2zG5OiM3LXcRuP6s5FmL4fuCMM/zvFAGBNIYgxuqOygpPfZCS2/duy+C1vUXOwOleEawibCT+7gPuBJODfhz08Ge3pGk8q2ZttOVM+CU+W6w11DmBduECAwEAAQ==-----END PUBLIC KEY-----`


export const publicEncryptedData = (data,type)=>{
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(pubKey)
  if(type === 'encrypt'){
    return encryptor.encrypt(data)
  }else if(type === 'decrypt'){
    return encryptor.decrypt(data)
  }
}

export const privateEncryptedData = (data,type)=>{
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey)
  if(type === 'encrypt'){
    return encryptor.encrypt(data)
  }else if(type === 'decrypt'){
    return encryptor.decrypt(data)
  }
}
